<template>
  <el-dialog drag v-model="show" width="450px" title="图片上传" center draggable append-to-body>
    <el-upload
      ref="uploader"
      :headers="headers"
      action="/api/editor?action=image"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :auto-upload="false"
      :on-change="uploadChange"
      accept=".jpg,.jpeg,.png,.gif"
    >
      <el-image style="width: 400px" :src="imgUrl" fit="contain" lazy>
        <template #error>
          <el-empty description="图片加载失败（非图片格式或图片不存在）" :image-size="100">
            <template #image>
              <el-icon size="70px">
                <Picture />
              </el-icon>
            </template>
          </el-empty>
        </template>
      </el-image>
      <template #tip>
        <p style="text-align: center; color: #909399; line-height: 40px; height: 20px">
          点击图片可上传或替换
        </p>
      </template>
    </el-upload>

    <template #footer>
      <el-button type="primary" @click="save" auto-insert-space :disabled="imgUrl == oriImgUrl">保存</el-button>
      <el-button @click="reset" auto-insert-space>重置</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, getCurrentInstance } from 'vue'
import { useAuthStore } from '@/stores/user'
import { defineEmits } from 'vue'
let uploader = ref()
let imgUrl = ref('')
let oriImgUrl = ''
let show = ref(false)

const emit = defineEmits(['upload-success'])

function open(url) {
  show.value = true
  imgUrl.value = url
  oriImgUrl = url
}
const store = useAuthStore()

const handleAvatarSuccess = (response, uploadFile) => {
  emit('upload-success', response.data.url)
  ElMessage({type:'success',message:'图片上传成功'})
  show.value = false
}

let headers = { Authorization: store.user.token }

const save = () => {
  ElMessageBox.confirm('确定要保存吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    uploader.value.submit()
  })
}

const reset = () => {
  imgUrl.value = oriImgUrl
}

function uploadChange(file) {
  imgUrl.value = URL.createObjectURL(file.raw)
}

defineExpose({ open })
</script>
